<template>
  <div class="app-container">
    <div class="top">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/static-site/static-site/' }">静态网站管理</el-breadcrumb-item>
        <el-breadcrumb-item>{{ siteName }} - 页面管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="top">
      <el-input
        v-model="kwInput"
        placeholder="输入页面标题进行筛选"
        class="input-with-select"
        clearable
        @keyup.native.enter="handleSearch"
      >
        <el-select slot="prepend" v-model="selectedStatus" placeholder="状态" clearable>
          <el-option label="全部" value="" />
          <el-option label="草稿" value="draft" />
          <el-option label="已发布" value="published" />
          <el-option label="已归档" value="archived" />
        </el-select>
        <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
      </el-input>
      <el-button
        type="primary"
        class="el-icon-plus add-btn"
        :disabled="listLoading"
        @click="handleAction('create', '添加页面')"
      >添加页面
      </el-button>
    </div>

    <el-table
      v-loading.body="listLoading"
      :data="data"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="handleSort"
      @selection-change="handleSelectionChange"
    >

      <el-table-column type="selection" width="55" align="center" />
      <el-table-column align="center" width="80" prop="id" label="ID" sortable="custom" />

      <el-table-column align="left" label="页面标题" min-width="200">
        <template slot-scope="scope">
          <el-link v-if="scope.row.status === 'published'" :href="scope.row.get_full_url" target="_blank" type="primary">
            {{ scope.row.title }}
          </el-link>
          <span v-else>{{ scope.row.title }}</span>
          <el-tag v-if="scope.row.is_home_page" size="mini" type="warning" style="margin-left: 5px">首页</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="别名" prop="slug" width="120">
        <template slot-scope="scope">
          <el-tag type="info" size="small">{{ scope.row.slug }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="分类" width="120">
        <template slot-scope="scope">
          <el-tag v-if="getCategoryName(scope.row.category_id)" size="small">{{ getCategoryName(scope.row.category_id) }}</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="状态" width="100">
        <template slot-scope="scope">
          <el-tag :type="statusTypeMap[scope.row.status]" size="small">
            {{ statusTextMap[scope.row.status] }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="访问量" prop="view_count" width="80" />

      <el-table-column align="center" label="发布时间" prop="publish_at" width="160">
        <template slot-scope="scope">
          <span>{{ scope.row.publish_at || '-' }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="380">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handlePreview(scope.row)">预览</el-button>
          <el-button
            v-if="scope.row.status !== 'published'"
            size="mini"
            type="success"
            @click="handlePublish(scope.row)"
          >发布</el-button>
          <el-button
            v-if="scope.row.status === 'published'"
            size="mini"
            type="warning"
            @click="handleUnpublish(scope.row)"
          >取消发布</el-button>
          <el-button size="mini" type="info" @click="handleAction('edit', scope.row)">编辑</el-button>
          <el-button size="mini" plain title="重构菜单" @click="handleRebuildMenu(scope.row)">
            <i class="el-icon-menu" />
          </el-button>
          <el-button size="mini" type="danger" @click="handleAction('delete', scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-show="total>0"
      background
      :current-page="listQuery.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="listQuery.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
    />

    <!-- 批量操作按钮 -->
    <div v-show="multipleSelection.length > 0" class="batch-actions">
      <el-button
        type="primary"
        icon="el-icon-folder-add"
        @click="handleGenerateDirectory"
      >
        生成分类 (已选择 {{ multipleSelection.length }} 项)
      </el-button>
      <el-button
        type="warning"
        icon="el-icon-menu"
        @click="handleBatchRebuildMenu"
      >
        重构菜单 (已选择 {{ multipleSelection.length }} 项)
      </el-button>
    </div>

    <el-drawer
      :title="title"
      :visible.sync="dialogVisible"
      direction="rtl"
      size="80%"
      :close-on-press-escape="false"
      :wrapper-closable="false"
    >
      <div class="drawer-content">
        <el-form v-if="action !== 'delete'" :model="temp" label-position="top">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="页面标题">
                <el-input v-model="temp.title" placeholder="请输入页面标题" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="页面别名">
                <el-input v-model="temp.slug" placeholder="请输入页面别名（用于URL）" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="所属分类">
                <el-select v-model="temp.category" placeholder="请选择分类（可选）" clearable filterable style="width: 100%;">
                  <el-option
                    v-for="item in categories"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="状态">
                <el-select v-model="temp.status" placeholder="请选择状态" style="width: 100%;">
                  <el-option label="草稿" value="draft" />
                  <el-option label="已发布" value="published" />
                  <el-option label="已归档" value="archived" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="排序">
                <el-input-number v-model="temp.sort_order" :min="0" :max="9999" placeholder="数字越小排序越前" style="width: 100%;" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="SEO描述">
                <el-input v-model="temp.meta_description" type="textarea" :rows="3" placeholder="请输入SEO描述" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="SEO关键词">
                <el-input v-model="temp.meta_keywords" type="textarea" :rows="3" placeholder="请输入SEO关键词，用逗号分隔" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="实际链接地址">
            <el-input v-model="temp.actual_url" placeholder="请输入页面的实际访问链接（可选）" />
            <div style="font-size: 12px; color: #999; margin-top: 5px;">
              用于AI生成分类页面时的产品链接，不填写则使用默认链接
            </div>
          </el-form-item>

          <el-form-item label="设置">
            <el-checkbox v-model="temp.is_home_page">设为首页</el-checkbox>
          </el-form-item>

          <el-form-item label="HTML内容">
            <el-input
              v-model="temp.html_content"
              type="textarea"
              :rows="20"
              placeholder="请输入HTML内容"
              style="font-family: 'Courier New', monospace;"
            />
          </el-form-item>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="CSS样式">
                <el-input
                  v-model="temp.css_content"
                  type="textarea"
                  :rows="10"
                  placeholder="请输入CSS样式（可选）"
                  style="font-family: 'Courier New', monospace;"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="JavaScript">
                <el-input
                  v-model="temp.js_content"
                  type="textarea"
                  :rows="10"
                  placeholder="请输入JavaScript代码（可选）"
                  style="font-family: 'Courier New', monospace;"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <div v-if="action === 'delete'" style="text-align: center; font-size: 16px; padding: 50px;">
          确认要删除页面 <strong>{{ temp.title }}</strong> 吗？
          <br><br>
          <el-alert title="警告：删除操作不可恢复！" type="warning" show-icon />
        </div>

        <div class="drawer-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 预览对话框 -->
    <el-dialog
      title="页面预览"
      :visible.sync="previewVisible"
      width="90%"
      top="5vh"
      :close-on-click-modal="false"
    >
      <div class="preview-container">
        <div class="preview-header">
          <el-tag type="info">{{ previewPage.title }}</el-tag>
          <span style="margin-left: 10px; color: #666;">{{ previewPage.slug }}</span>
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-full-screen"
            style="float: right;"
            @click="openFullPreview"
          >
            全屏预览
          </el-button>
        </div>
        <div class="preview-iframe-container">
          <iframe
            ref="previewFrame"
            :srcdoc="previewHtml"
            width="100%"
            height="600px"
            frameborder="0"
            sandbox="allow-scripts allow-same-origin"
          />
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="previewVisible = false">关 闭</el-button>
      </span>
    </el-dialog>

    <!-- 全屏预览对话框 -->
    <el-dialog
      title="全屏预览"
      :visible.sync="fullPreviewVisible"
      width="95%"
      top="2vh"
      :close-on-click-modal="false"
      custom-class="full-preview-dialog"
    >
      <div class="full-preview-container">
        <iframe
          :srcdoc="previewHtml"
          width="100%"
          height="80vh"
          frameborder="0"
          sandbox="allow-scripts allow-same-origin"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="fullPreviewVisible = false">关 闭</el-button>
      </span>
    </el-dialog>

    <!-- AI任务组件 -->
    <AITask
      v-if="aiTaskVisible"
      ref="aiTask"
      task-name="ai_generate_static_site_category"
      :params="aiTaskParams"
      :show-name="`根据 ${multipleSelection.length} 个页面生成分类`"
      dialog-title="AI生成分类"
      button-text="生成分类"
      :show-icon="false"
      @final-result="handleAITaskResult"
      @apply="handleAITaskApply"
      @close="handleAITaskClose"
    />

    <!-- AI菜单重构日志对话框 -->
    <el-dialog
      :title="currentRebuildPage ? `重构页面菜单: ${currentRebuildPage.title}` : '批量重构页面菜单'"
      :visible.sync="menuRebuildLogVisible"
      width="70%"
      :close-on-click-modal="false"
      :show-close="!menuRebuildLoading"
    >
      <div class="menu-rebuild-log" style="height: 400px; overflow-y: auto; background: #f5f5f5; padding: 10px; border-radius: 4px; font-family: monospace; font-size: 12px; line-height: 1.4; white-space: pre-wrap;">
        {{ menuRebuildLog }}
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button
          :loading="menuRebuildLoading"
          :disabled="menuRebuildLoading"
          @click="menuRebuildLogVisible = false"
        >
          {{ menuRebuildLoading ? '重构中...' : '关闭' }}
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  getStaticSitePageList,
  createStaticSitePage,
  updateStaticSitePage,
  deleteStaticSitePage,
  publishStaticSitePage,
  unpublishStaticSitePage,
  getStaticSiteCategoryList,
  aiRebuildPageMenuStream,
  batchRebuildPagesMenuStream
} from '@/api/spider/static_site'
import AITask from '@/components/AITask'

export default {
  name: 'StaticSitePage',
  components: {
    AITask
  },
  data() {
    return {
      data: [],
      listLoading: true,
      kwInput: '',
      selectedStatus: '',
      listQuery: {
        page: 1,
        pageSize: 20
      },
      total: 0,
      siteId: null,
      siteName: '',
      categories: [],
      multipleSelection: [], // 多选数据

      statusTypeMap: {
        'draft': 'info',
        'published': 'success',
        'archived': 'warning'
      },
      statusTextMap: {
        'draft': '草稿',
        'published': '已发布',
        'archived': '已归档'
      },

      action: null,
      dialogVisible: false,
      title: '',
      temp: {
        title: '',
        slug: '',
        category: null,
        meta_description: '',
        meta_keywords: '',
        html_content: '',
        css_content: '',
        js_content: '',
        actual_url: '',
        status: 'draft',
        is_home_page: false,
        sort_order: 0
      },

      // 预览相关
      previewVisible: false,
      fullPreviewVisible: false,
      previewPage: {},
      previewHtml: '',

      // AI任务相关
      aiTaskParams: {},
      aiTaskVisible: false,

      // AI菜单重构相关
      menuRebuildLoading: false,
      menuRebuildLogVisible: false,
      menuRebuildLog: '',
      currentRebuildPage: null

    }
  },
  created() {
    this.siteId = this.$route.query.site_id
    this.siteName = this.$route.query.site_name || '未知网站'
    if (!this.siteId) {
      this.$message.error('缺少网站ID参数')
      this.$router.push('/static-site/static-site/')
      return
    }
    this.getList()
    this.getCategories()
  },
  methods: {
    getCategoryName(categoryId) {
      if (!categoryId || !this.categories.length) {
        return ''
      }
      const category = this.categories.find(cat => cat.id === categoryId)
      return category ? category.name : ''
    },
    resetTemp() {
      this.temp = {
        title: '',
        slug: '',
        category: null,
        meta_description: '',
        meta_keywords: '',
        html_content: '',
        css_content: '',
        js_content: '',
        actual_url: '',
        status: 'draft',
        is_home_page: false,
        sort_order: 0,
        site: this.siteId
      }
    },
    getList() {
      this.listLoading = true
      const params = {
        page: this.listQuery.page,
        pageSize: this.listQuery.pageSize,
        site_id: this.siteId
      }
      if (this.kwInput) {
        params.search = this.kwInput
      }
      if (this.selectedStatus) {
        params.status = this.selectedStatus
      }

      getStaticSitePageList(new URLSearchParams(params).toString())
        .then(response => {
          if (response.success) {
            this.data = response.data.data
            this.total = response.data.total
          } else {
            this.$message.error('获取数据失败：' + response.msg)
          }
          this.listLoading = false
        }).catch(err => {
          console.log(err)
          this.$message.error('获取数据失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
          this.listLoading = false
        })
    },
    getCategories() {
      const params = {
        site_id: this.siteId
      }
      getStaticSiteCategoryList(new URLSearchParams(params).toString())
        .then(response => {
          if (response.success) {
            this.categories = response.data.data
          }
        }).catch(err => {
          console.log('获取分类失败:', err)
        })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.title = '添加页面'
          this.resetTemp()
          this.dialogVisible = true
          break
        case 'edit':
          this.title = '编辑页面'
          this.temp = Object.assign({}, row)
          this.temp.site = this.siteId
          this.temp.category = row.category_id || null
          this.dialogVisible = true
          break
        case 'delete':
          this.title = '删除确认'
          this.temp = Object.assign({}, row)
          this.dialogVisible = true
          break
      }
    },
    confirm() {
      const _data = this.temp
      switch (this.action) {
        case 'create':
          createStaticSitePage(_data).then(response => {
            if (response.success) {
              this.dialogVisible = false
              this.getList()
              this.notify('添加成功')
            } else {
              this.$message.error('添加失败：' + response.msg)
            }
          }).catch(err => {
            this.$message.error('添加失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
          })
          return
        case 'edit':
          updateStaticSitePage(_data.id, _data).then(response => {
            if (response.success) {
              this.dialogVisible = false
              this.getList()
              this.notify('更新成功')
            } else {
              this.$message.error('更新失败：' + response.msg)
            }
          }).catch(err => {
            this.$message.error('更新失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
          })
          return
        case 'delete':
          deleteStaticSitePage(_data.id).then(response => {
            if (response.success) {
              this.dialogVisible = false
              this.getList()
              this.notify('删除成功')
            } else {
              this.$message.error('删除失败：' + response.msg)
            }
          }).catch(err => {
            this.$message.error('删除失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
          })
          return
      }
    },
    handlePublish(row) {
      publishStaticSitePage(row.id).then(response => {
        if (response.success) {
          this.getList()
          this.notify('发布成功')
        } else {
          this.$message.error('发布失败：' + response.msg)
        }
      }).catch(err => {
        this.$message.error('发布失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
      })
    },
    handleUnpublish(row) {
      unpublishStaticSitePage(row.id).then(response => {
        if (response.success) {
          this.getList()
          this.notify('取消发布成功')
        } else {
          this.$message.error('取消发布失败：' + response.msg)
        }
      }).catch(err => {
        this.$message.error('取消发布失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
      })
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handlePageChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleSearch() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSort(v) {
      console.log('排序:', v)
    },
    handleSelectionChange(selection) {
      this.multipleSelection = selection
    },
    handleGenerateDirectory() {
      // 使用 AITask 组件实现生成分类功能
      console.log('生成分类，选中的数据:', this.multipleSelection)

      if (!this.multipleSelection || this.multipleSelection.length === 0) {
        this.$message.warning('请先选择要生成分类的页面')
        return
      }

      // 确认对话框
      this.$confirm(
        `确定要为选中的 ${this.multipleSelection.length} 个页面生成分类吗？`,
        '生成分类确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }
      ).then(() => {
        this.processGenerateCategory()
      }).catch(() => {
        this.$message.info('已取消生成分类')
      })
    },
    processGenerateCategory() {
      // 准备参数
      const pageIds = this.multipleSelection.map(page => page.id)
      const siteId = this.siteId

      // 构建页面信息提示，作为用户额外要求
      const pageInfo = this.multipleSelection.map(page =>
        `- ${page.title} (ID: ${page.id})`
      ).join('\n')

      const userContent = `Please generate a category for the following pages:

Site Information:
- Site Name: ${this.siteName}
- Site ID: ${siteId}

Selected Pages (${pageIds.length} pages):
${pageInfo}

Please generate an appropriate category based on the titles, descriptions, keywords and other information of these pages, including:
1. Category Name
2. Category Slug (URL slug)
3. Category Description
4. Anchor Text Keywords`

      // 设置AITask参数
      this.aiTaskParams = {
        page_ids: pageIds,
        site_id: siteId,
        user_content: userContent
      }

      // 显示AITask组件
      this.aiTaskVisible = true

      // 等待组件渲染完成后手动打开对话框
      this.$nextTick(() => {
        if (this.$refs.aiTask) {
          this.$refs.aiTask.handleShowDialog()
        }
      })
    },
    handleAITaskResult(result) {
      // AI任务最终结果处理
      console.log('AI任务最终结果:', result)

      try {
        const finalResult = typeof result === 'string' ? JSON.parse(result) : result
        if (finalResult.success) {
          this.$message.success(`分类生成成功：${finalResult.name}`)
        } else {
          this.$message.error('分类生成失败')
        }
      } catch (error) {
        console.error('解析AI任务结果失败:', error)
        this.$message.warning('分类生成过程完成，请检查分类列表')
      }

      // 刷新分类列表
      this.getCategories()
      // 清空选择
      this.multipleSelection = []
    },
    handleAITaskApply(result) {
      // AI任务应用结果
      console.log('AI任务应用结果:', result)
      this.handleAITaskResult(result.final_result || result.content)
    },
    handleAITaskClose() {
      // AI任务对话框关闭
      this.aiTaskVisible = false
      // 刷新分类列表
      this.getCategories()
    },
    handlePreview(row) {
      this.previewPage = row
      this.generatePreviewHtml(row)
      this.previewVisible = true
    },
    generatePreviewHtml(page) {
      const html = page.html_content || this.getDefaultContent()
      const css = page.css_content || ''
      const js = page.js_content || ''

      // 简单的字符串拼接，直接在头部插入CSS和JS
      let previewContent = html

      if (css) {
        const styleTag = '<' + 'style>' + css + '</' + 'style>'
        previewContent = styleTag + previewContent
      }

      if (js) {
        const scriptTag = '<' + 'script>' + js + '</' + 'script>'
        previewContent = scriptTag + previewContent
      }

      this.previewHtml = previewContent
    },
    getDefaultContent() {
      return '<p>暂无HTML内容</p>'
    },
    openFullPreview() {
      this.previewVisible = false
      this.fullPreviewVisible = true
    },

    // AI菜单重构相关方法
    handleRebuildMenu(page) {
      this.$confirm('确定要重构此页面的菜单吗？此操作将用数据库中的菜单配置替换页面中的菜单部分，内容部分保持不变。', '确认重构', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.rebuildPageMenu(page)
      }).catch(() => {
        // 用户取消
      })
    },

    handleBatchRebuildMenu() {
      if (!this.multipleSelection.length) {
        this.$message.warning('请先选择要重构的页面')
        return
      }

      this.$confirm(`确定要重构选中的 ${this.multipleSelection.length} 个页面的菜单吗？此操作将用数据库中的菜单配置替换页面中的菜单部分，内容部分保持不变。`, '确认批量重构', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.batchRebuildPagesMenu()
      }).catch(() => {
        // 用户取消
      })
    },

    async rebuildPageMenu(page) {
      this.menuRebuildLoading = true
      this.currentRebuildPage = page
      this.menuRebuildLog = ''
      this.menuRebuildLogVisible = true

      try {
        const apiKey = this.$store.getters.ai_task_api_key || 'test_key_for_development'
        if (!apiKey) {
          this.$message.error('请先在系统设置中配置AI API密钥')
          return
        }

        const requestData = {
          page_id: page.id,
          api_key: apiKey,
          engine: 'default'
        }

        await aiRebuildPageMenuStream(
          requestData,
          (message) => {
            // 进度更新
            this.menuRebuildLog += message
            this.$nextTick(() => {
              // 滚动到底部
              const logElement = document.querySelector('.menu-rebuild-log')
              if (logElement) {
                logElement.scrollTop = logElement.scrollHeight
              }
            })
          },
          (result) => {
            // 完成
            this.menuRebuildLoading = false
            this.menuRebuildLog += '\n\n=== 重构完成 ===\n'
            this.menuRebuildLog += `页面ID: ${result.page_id}\n`
            this.menuRebuildLog += `页面标题: ${result.page_title}\n`
            this.menuRebuildLog += `重构状态: ${result.success ? '成功' : '失败'}\n`
            this.menuRebuildLog += `集成的菜单类型: ${result.menu_types_integrated ? result.menu_types_integrated.join(', ') : '无'}\n`
            this.menuRebuildLog += `菜单项总数: ${result.total_menu_items || 0}\n`

            if (result.success) {
              this.$message.success('页面菜单重构完成')
              this.getList() // 刷新列表
            } else {
              this.$message.error('页面菜单重构失败')
            }
          },
          (error) => {
            // 错误
            this.menuRebuildLoading = false
            this.menuRebuildLog += '\n\n❌ 重构失败: ' + error + '\n'
            this.$message.error('页面菜单重构失败: ' + error)
          }
        )
      } catch (error) {
        this.menuRebuildLoading = false
        this.menuRebuildLog += '\n\n❌ 重构失败: ' + error.message + '\n'
        this.$message.error('页面菜单重构失败: ' + error.message)
      }
    },

    async batchRebuildPagesMenu() {
      this.menuRebuildLoading = true
      this.menuRebuildLog = ''
      this.menuRebuildLogVisible = true

      try {
        const apiKey = this.$store.getters.ai_task_api_key || 'test_key_for_development'
        if (!apiKey) {
          this.$message.error('请先在系统设置中配置AI API密钥')
          return
        }

        const pageIds = this.multipleSelection.map(page => page.id)
        const requestData = {
          page_ids: pageIds,
          api_key: apiKey,
          engine: 'default'
        }

        await batchRebuildPagesMenuStream(
          requestData,
          (message) => {
            // 进度更新
            this.menuRebuildLog += message
            this.$nextTick(() => {
              // 滚动到底部
              const logElement = document.querySelector('.menu-rebuild-log')
              if (logElement) {
                logElement.scrollTop = logElement.scrollHeight
              }
            })
          },
          (result) => {
            // 完成
            this.menuRebuildLoading = false
            this.menuRebuildLog += '\n\n=== 批量重构完成 ===\n'
            this.menuRebuildLog += `总页面数: ${result.total_pages}\n`
            this.menuRebuildLog += `成功重构: ${result.successful_pages}\n`
            this.menuRebuildLog += `失败数量: ${result.failed_pages}\n`
            this.menuRebuildLog += `整体状态: ${result.success ? '成功' : '失败'}\n`

            if (result.success) {
              this.$message.success(`批量重构完成：成功 ${result.successful_pages} 个，失败 ${result.failed_pages} 个`)
              this.getList() // 刷新列表
              this.multipleSelection = [] // 清空选择
            } else {
              this.$message.error('批量重构失败')
            }
          },
          (error) => {
            // 错误
            this.menuRebuildLoading = false
            this.menuRebuildLog += '\n\n❌ 批量重构失败: ' + error + '\n'
            this.$message.error('批量重构失败: ' + error)
          }
        )
      } catch (error) {
        this.menuRebuildLoading = false
        this.menuRebuildLog += '\n\n❌ 批量重构失败: ' + error.message + '\n'
        this.$message.error('批量重构失败: ' + error.message)
      }
    }
  }
}
</script>

<style scoped>
.top {
  padding-left: 20px;
  margin-bottom: 30px;
  margin-top: 28px;
}

.top >>> .el-select .el-input {
  width: 120px;
}

.top >>> .input-with-select .el-input-group__prepend {
  background-color: #fff;
}

.input-with-select {
  width: calc(100% - 200px);
}

.add-btn {
  float: right;
  margin-right: 20px;
  width: 150px
}

.app-container >>> .el-dialog {
  margin-top: 48px !important;
  margin-bottom: 68px;
}

.mt-dialog >>> .el-dialog {
  margin: 88px auto !important;
}

.preview-container {
  height: 100%;
}

.preview-header {
  padding: 10px 0;
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 15px;
}

.preview-iframe-container {
  width: 100%;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.full-preview-dialog >>> .el-dialog__body {
  padding: 10px 20px;
}

.full-preview-container {
  width: 100%;
  height: 100%;
}

/* 抽屉样式 */
.drawer-content {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
}

.drawer-footer {
  position: fixed;
  bottom: 0;
  right: 0;
  width: 80%;
  padding: 20px;
  background: #fff;
  border-top: 1px solid #e4e7ed;
  text-align: right;
  z-index: 1000;
}

/* 确保内容区域底部有足够空间 */
.drawer-content {
  padding-bottom: 80px;
}

/* 批量操作按钮样式 */
.batch-actions {
  margin: 20px 0;
  text-align: center;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e9ecef;
}

.batch-actions .el-button {
  font-size: 14px;
  padding: 12px 30px;
}
</style>
